import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  var counter = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('data share'),
      ),
      body: A(
        counter,
        child: B(
          child: F(),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            counter++;
          });
        },
      ),
    );
  }
}

class A extends InheritedWidget {
  //int counter = 0;
  late ValueNotifier<int> _valueNotifier;
  A(int counter, {required Widget child}) : super(child: child) {
    _valueNotifier = ValueNotifier<int>(counter);
  }
  ValueNotifier<int> get valueNotifier => _valueNotifier;

  static A of(BuildContext context) {
    // return context.dependOnInheritedWidgetOfExactType<A>();
    return context.getElementForInheritedWidgetOfExactType<A>()?.widget as A;
  }

  add(newdata) {
    _valueNotifier.value = newdata;
  }

  @override
  bool updateShouldNotify(covariant A old) {
    return false;
  }
}

class B extends StatefulWidget {
  final Widget child;
  const B({Key? key, required this.child}) : super(key: key);

  @override
  State<B> createState() => _BState();
}

class _BState extends State<B> {
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print('B didChangeDependencies');
  }

  @override
  Widget build(BuildContext context) {
    print('B build');
    return Container(
      child: this.widget.child,
    );
  }
}

class F extends StatefulWidget {
  const F({Key? key}) : super(key: key);

  @override
  State<F> createState() => _FState();
}

class _FState extends State<F> {
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print('F didChangeDependencies');
  }

  @override
  Widget build(BuildContext context) {
    print('F build');
    return ValueListenableBuilder(
      valueListenable: A.of(context).valueNotifier,
      builder: (BuildContext context, int value, Widget? child) {
        return Column(children: [
          Container(
            child: Text(
              'tangguodalong--${value}',
              textScaleFactor: 2,
            ),
          ),
          ElevatedButton.icon(
              onPressed: () {
                A.of(context).add(++A.of(context).valueNotifier.value);
                print(A.of(context).valueNotifier.value);
              },
              icon: Icon(Icons.add),
              label: Text('添加')),
        ]);
      },
    );
  }
}
